layui.define(["form","laydate","button"],function(exports) {
	
    class Search {
        constructor (opt){
            if($("#"+opt.id).length<1){return alert("查询控件容器不存在");}
            this.$opt = opt;
            this.$el=$("#"+opt.id);
            this._initHtml(opt);
        }
        _getStyle(){
            let html=`<style type="text/css"></style>`;
            return '';
            return $.trim(html);
        }
        _initHtml(opt){
            var $th=this;
            function _getQuery(){
                let html="";
                $.each(opt.query, function(index,o) {
                    if(o.type==="checkbox" || o.type==="radio"){
                        html+=`
                            <div class="layui-input-inline">
                                <label data-opera="${o.opera}">${o.title || o.name || ''}</label>
                                <div class="layui-input-inline">${$th._getDomType(o)}</div>
                            </div>
                        `;
                    }else{
                        html+=`<div class="layui-input-inline">${$th._getDomType(o)}</div>`;
                    }
                });
                return html;
            }
            function _getSeniorSearch(){
                let html="";
                if(opt.queryMore && opt.queryMore[0]){
                    let length=opt.queryMore.length;
                    let cols = opt.queryMoreCols || 3;
                    let colLength = Math.ceil(length / cols);
                    for (var  i = 1 ; i < colLength + 1; i++ ) {
                    	html +="<tr>";
                        $.each(opt.queryMore, function(k,o) {
                            let isCols = (i == 1 && (k+ 1) <= cols  ||  (k + 1) > cols * (i-1) && k < cols * i);
                            if(isCols){
                                html+=`<td>${o.title || o.name || ''}</td><td>${$th._getDomType(o)}</td>`;
                            }
                        });
                        html+="</tr>";
                    }
                }
                return html;
            }
            var html=`
                ${this._getStyle()}
                <div class="layui-form xw-search" lay-filter="xw-search">
                    <div class="xw-search-title">筛选：</div>
                    <div class="xw-search-input">
                        ${  _getQuery() }
                        <div class='layui-input-inline' style='margin-right: 0;'>
                            <button class="layui-btn  layui-btn-sm xw-searchQuery">搜索</button>
                        </div>
                       ${opt.htmls ? ' <div class="layui-input-inline" style="margin-left: 15px;">'+ $.htmlDecode(opt.htmls) + '</div>' : '' }
                        <div class="xw-seniorSearchBtn">
                        	<div class="fl">
                        		${opt.btns ?  layui.button.getBtn(opt.btns) : ''}
                        	</div>
                    		<button class="layui-btn layui-btn-primary layui-btn-sm emptyBtn" style="display:${opt.showEmptyBtn =='true' ? 'block' : 'none' };margin-left:50px;">重置</button>
                            <button class="layui-btn layui-btn-primary layui-btn-sm seniorSearchBtn" style="display:${opt.queryMore && opt.queryMore[0] ? 'block' : 'none' };margin-left:${  opt.showEmptyBtn =='true' ? '5px' : '50px'};">高级<i class="iconfont" style="line-height: 0;">&#xe60d;</i></button>
                        </div>
                    </div>
                </div>
                <div class="layui-form xw-seniorSearch" lay-filter="xw-seniorSearch" style="display: none;">
                    <div class="inputArea">
                        <table width="100%" border="0" cellspacing="0" cellpadding="0">
                            <tr>
                                <th style="width:1px;max-width: 1px;"></th><th></th>
                                <th style="width:1px;max-width: 1px;"></th><th></th>
                                <th style="width:1px;max-width: 1px;"></th><th></th>
                                <th style="width:1px;max-width: 1px;"></th><th></th>
                                <th style="width:1px;max-width: 1px;"></th><th></th>
                            </tr>
                            ${  _getSeniorSearch() }
                        </table>
                    </div>
                    <div class="btnWarp">
                        <button class="layui-btn layui-btn-normal layui-btn-sm xw-searchQuery">
                            <i class="el-icon-search"></i>搜索
                        </button>
                    </div>
                </div> 
            `;
            $th.$el.css("height","100%").html(" ").html(html);
            $th._initEvent();
        }
        
        //获取dom类型
        _getDomType(data){
        	let that = this;
            let html="";
            
            //获取下拉选择框
            function getOptionsHtml(data){
                let html=``;
                $.each(data.options, function(index,o) {
                    let selected = o.value == data.value ? "selected" : "";
                    var localStorageValue = localStorage[ 'xwSearch_select_' + data.field];
                    if(data.saveLog == "true" && localStorageValue && o.value == localStorageValue){
                    	selected = "selected";
                    }
                    html+=`<option value="${o.value}"  ${selected}>${o.label}</option>`;
                });
                if(data.url){
                    $.ajaxs(data.url,null,function(res){
                        data.options=res.data;
                    },false);
                }
                return html;
            }
            
            //获取复选框
            function getCheckboxHtml(){
                let  html="";
                if(data.url){
                    $.ajaxs(data.url,null,function(res){
                        data.options=res.data;
                    },false);
                }
                $.each(data.options, function(index,o) {
                    let selected = o.value == data.value ? "checked" : "";
                    html+=`
                    	<input lay-filter="xwSearch_${that.$opt.id}" type="checkbox" lay-skin="primary"
                    		data-opera="${data.opera}"  
                    		name="${data.field}" 
                    		title="${o.label}" 
                    		value="${o.value}"
                    		${selected} 
                    	>`;
                });
                return html;
            }
            
            //获取单选框
            function getRadioHtml(){
                let  html="";
                if(data.url){
                    $.ajaxs(data.url,null,function(res){
                        data.options=res.data;
                    },false);
                }
                $.each(data.options, function(index,o) {
                    let selected = o.value == data.value ? "checked" : "";
                    html+=`
                    	<input lay-filter="xwSearch_${that.$opt.id}" type="radio" lay-skin="primary"
                    		data-opera="${data.opera}"  
                    		name="${data.field}" 
                    		title="${o.label}"  
                    		value="${o.value}" 
                    		${selected} 
                    	>`;
                });
                return html;
            }
            switch(data.type){
            	case "selectTree":
	                html= `
	                	<input form-dataType="selectTree" type="text" class="layui-input" readonly
	                		placeholder="${data.title || data.name || ''}"
	                		id="${$.createGuid()}"
	                        name="${data.field}"
	                        data-opera="${data.opera}"
	                        data-url="${data.dataUrl || ''}"
	                        text-field="${data.textField || ''}"
	                        id-field="${data.idField || ''}"
	                        parent-field="${data.parentField || ''}"
	                        show-checkbox= "${data.showCheckbox || ''}",  
	                    />
	            	`;
                    break;
                case "select":
	                html= `
	                	<select lay-search lay-filter="xwSearch_${that.$opt.id}"
	                		data-opera="${data.opera}"
		            		name="${data.field}"
		            		savelog="${data.saveLog}"
	            		>${getOptionsHtml(data)}</select>
	            	`;
                    break;
                case "multiSelect":
                    html =` 
                        <select xm-select="${$.createGuid()}"
                        	form-dataType="multiSelect"
                            xm-select-height="30px" 
                            xm-select-show-count="${2}"
                            name="${data.field}"
                            data-opera="${data.opera}"
                            >${getOptionsHtml(data)}</select>
                        `;
                    break;        
                case "checkbox":
                    html=getCheckboxHtml(data);
                    break;
                case "radio":
                    html=getRadioHtml(data);
                    break;
                case "datetime":
                    html=`
                        <input datetime="datetime" readonly type="text"  class="layui-input" 
	                        data-opera="${data.opera}" 
	                        name="${data.field}" 
	                        min="${data.min || ''}" 
	                        max="${data.max || ''}" 
	                        value="${data.value || ''}"
	                        format="${data.format || ''}" 
	                        placeholder="${data.title || data.name || ''}"  
                    	>`;    
                    break;
                case "daterange":
                    html=`
                        <input datetime="daterange" readonly type="text" class="layui-input" 
                        	data-opera="${data.opera}" 
                        	name="${data.field}" 
                        	placeholder="${data.title || data.name || ''}"  
                        >`;    
                    break;
                case "html":
                    html=`<div class="xw-search_html_type ${data.class || ''}"
                    	style="${data.style || ''}"
                    	id="${data.id}"
                    	data-opera="${data.opera}"
                    	name="${data.field}"
                    ></div>`;
                    break;    
                case "blank":
                    html=`<div class="xw-search_html_type"></div>`;
                    break;        
                case "hidden":
                    html=`<input  type="hidden"  class="layui-input"
	                        data-opera="${data.opera}"
	                        value="${data.value || ''}" 
	                        name="${data.field || ''}" 
	                        placeholder="${ data.title || data.name || ''}"
                        >`;
                    break;        
                default:
                    html=`
                        <input  type="text"  class="layui-input"
	                        data-opera="${data.opera}"
	                        value="${data.value || ''}" 
	                        name="${data.field || ''}" 
	                        placeholder="${ data.title || data.name || ''}"
	                        ${data.edit == "false" ?  "disabled" : ""}
                        >
                    `;    
            }
            return html;
        }
        
        //初始化事件
        _initEvent(){
            var $th=this;
            //初始化from
            layui.form.render(null, 'xw-search');
            layui.form.render(null, 'xw-seniorSearch');
            //如果是IE9，则处理placeholder
            function isShowPlaceholder(e){
        		if($(e).val().length>0){
	      			$(e).siblings(".layui-input-placeholder").hide();
	      		}else{
	      			$(e).siblings(".layui-input-placeholder").show();
	      		}
        	}
            if( $.isIE() == 9 ){
            	$.each($(".layui-input[placeholder]"), function(index,obj) {
		      		if($(this).siblings("span.layui-input-placeholder").length == 0 && $(this).val().length<1){
		      			var $span = $("<span class='layui-input-placeholder'>");
		      			$span.text( $(this).attr("placeholder"))
		      			$(this).before($span);
		      		}
		      	});
		      	$th.$el.on("click",'.layui-input-placeholder',function(){
		      		$(this).siblings(".layui-input").focus();
		      	});
		      	$th.$el.on('input propertychange','.layui-input',function(e){
		      		isShowPlaceholder($(this));
		      	});
		      	$th.$el.on('keyup','.layui-input',function(e){
		      		isShowPlaceholder($(this));
		      	});
		      	$th.$el.on('keydown','.layui-input',function(e){
		      		isShowPlaceholder($(this));
		      	});
		      	$th.$el.on('blur','.layui-input',function(e){
                    isShowPlaceholder($(this));
                });
            }
            //绑定时间事件
            $.each($th.$el.find("input[datetime]"), function(index,o) {
            	let that = $(this);
            	let min = $(o).attr("min");
                let max = $(o).attr("max");
                let format= $(o).attr("format");
            	layui.laydate.render({ 
            	    elem: o,
            	    format: format || 'yyyy-MM-dd', //可任意组合 yyyy-MM-dd HH:mm:ss
            	    position: 'abolute',
                    min: !min  || min == "undefined"?  "1900-1-1" : min,
                    max: !max || max == "undefined" ?  "2199-12-31" : max,
                    showBottom:true,
                    trigger:'click', //呼出控件的事件
            	    range:$(this).attr("datetime") != "datetime" ? true : false,
            	    type:$th._getFormat(format ||''),
            	    done: function(value, date, endDate){
                        setTimeout(function(){
                        	$th._queryFn($th.getData(),o); 
                        	isShowPlaceholder( that );
                        },10);
                    }
            	});
            });
            //下拉选中
       	 	layui.form.on(`select(xwSearch_${this.$opt.id})`, function(data){
       	 		if( $(data.elem).attr("savelog") == "true" || $(data.elem).attr("savelog") == true){
       	 			localStorage[ 'xwSearch_select_' + $(data.elem).attr('name') ] = $(data.elem).val();
       	 		}
        		isShowPlaceholder($(data.elem).siblings(".layui-form-select").find('.layui-input'));
           		setTimeout(function(){ $th._queryFn($th.getData(),data.elem); },10);
        	});
            //复选框选中
            layui.form.on(`checkbox(xwSearch_${this.$opt.id})`, function(data){
               !(function(_queryFn){ setTimeout(function(){ _queryFn($th.getData()); },10);  }( $th._queryFn ));
            });
            //单选框选中
            layui.form.on(`radio(xwSearch_${this.$opt.id})`, function(data){
               !(function(_queryFn){ setTimeout(function(){ _queryFn($th.getData()); },10);  }( $th._queryFn ));
            });
           //搜索按钮
            $th.$el.find(".xw-searchQuery").click(function(e){
               	e.clientX && $th._queryFn($th.getData());
            });
            //回车
            $th.$el.find('input[type="text"]').keydown(function(e){
                if (e.keyCode == 13) { 
                    $th._queryFn($th.getData(),e);
                }
            });
            //高级搜索按钮
            $th.$el.find(".seniorSearchBtn").click(function(){
                $th.$el.find(".xw-seniorSearch").toggle();
                var hidden=$th.$el.find(".xw-seniorSearch").is(":hidden");
                $(this).find("i").html( !hidden ?  "&#xe614;" : "&#xe60d;");
                if( $th.$opt.searchBtnFixed != 'true' ){
                	if(hidden){
	                    $th.$el.find(".xw-search .xw-searchQuery").show();
	                }else{
	                    $th.$el.find(".xw-search .xw-searchQuery").hide();
	                }
                }else{
                	$th.$el.find(".xw-seniorSearch .xw-searchQuery").hide();
                }
                $th._setHeight();
            });
            if(this.$opt.showMores == 'true' && this.$opt.queryMore && this.$opt.queryMore[0]){
            	$th.$el.find(".seniorSearchBtn").click();
            	if( $th.$opt.searchBtnFixed != 'true' ){
            		$th.$el.find(".xw-search .xw-searchQuery").hide();
            	}
            }
            
            //重置按钮
            $th.$el.find(".emptyBtn").click(function(){
            	$th.emptyData();
            });
            //下拉多选框初始化  //https://hnzzmsf.github.io/example/example_v4.html#select_on
            if($th.$el.find("select[xm-select]").length!=0){
                layui.formSelects.render();
                $.each($th.$el.find("select[xm-select]"), function(index,o) {
                    let id= $(o).attr("xm-select");
                   	$th.$el.find("[fs_id="+id+"]").attr("data-opera",$(o).attr("data-opera"));
                    $th.$el.find("[fs_id="+id+"]").attr("name",$(o).attr("_name"));
                    //['select', 'remove', 'reverse']
                    layui.formSelects.btns(id,['select','remove'],{show: '', space: '10px'});
                    layui.formSelects.on(id, function(e,data){
                        let vals = $.map(data,function(h){ return h.value; }).join(',');
                        $th.$el.find("[fs_id="+id+"]").attr("data-value",vals);
                        $th._queryFn($th.getData());
                    },true);
                });
            }
            //初始化下拉树
            if($th.$el.find("[form-dataType='selectTree']").length!=0){
            	$.each($th.$el.find("[form-dataType='selectTree']"), function() {
            		layui.selectTree.render({
		                elem: $(this),
		                textField: $(this).attr('text-field'),
		                idField: $(this).attr('id-field'),
		                parentField: $(this).attr('parent-field'),
		                data: $(this).attr('data-url') ,
		                isList:true,                                               
		                expandNode:1,
		                isDefaultSelected:true,
		                showCheckbox: $(this).attr('show-checkbox') || false,  
		                accordion: $(this).attr('accordion') || false, 		                          
		                showIcon: false,
		                disableParentNode:true,
		                selectedNode: function(obj){         
		                	$th._queryFn( $th.getData() );
		                }
		            });
            	});
            };
            
        }

        //获取时间格式
        _getFormat(format){
            let _format ='date';
            if(format.indexOf("d") == -1 && format)
                _format='month';
            if(format.indexOf("M") ==-1 && format)
                _format='year';
            if(format.indexOf("H") !=-1)
                _format='datetime';
            if(format == 'HH:mm:ss' || format == 'HH:mm' || format == 'HH:mm:ss' || format == 'HH')
                _format='time';    
            return _format;
        }
       
        //设置高度
        _setHeight(){
            var height= this.$el.parents(".wrapper").find(".panel-heading").outerHeight();
            if(height){
            	this.$el.parents(".wrapper").find(".content").css("height","calc(100% - "+ (height + 1)+"px)" );
            }
            var height= this.$el.parents(".xw__grid_search_body").outerHeight();
            if(height){
                this.$el.parents(".xw__grid").find(".xw__grid_grid_body")
                .css("height","calc(100% - "+height +"px)" );
            }
        }
        
        //设置值
        setValue(name,value){
            $(this.$el).find(`[name='${name}']`).val(value);
            layui.form.render(null, 'xw-search');
            layui.form.render(null, 'xw-seniorSearch');
        }
        
        //获取数据
        getData(dataField){
            let $th=this;
            let Array = [];
            function _fn(dom){
                let obj={};
                
                if($(dom).find("select").length){
                    obj.opera=$(dom).find("select").attr("data-opera");
                    obj.field = $(dom).find("select").attr("name");
                    obj.value = $(dom).find("select").val();
                }
                
                if($(dom).find(".xm-select-parent").length){
                    obj.opera=$(dom).find(".xm-select-parent").attr("data-opera");
                    obj.field = $(dom).find(".xm-select-parent").attr("name");
                    obj.value = $(dom).find(".xm-select-parent").attr("data-value");
                }
                
                if($(dom).find("input[type='radio']:checked").length){
                    obj.opera=$(dom).find("input[type='radio']:checked").attr("data-opera");
                    obj.field = $(dom).find("input[type='radio']:checked").attr("name");
                    obj.value = $(dom).find("input[type='radio']:checked").val();
                }
                
                let checkedBox = $(dom).find("input[type='checkbox']:checked");
                if(checkedBox.length){
                    obj.opera="in";
                    obj.field = checkedBox.attr("name");
                    obj.value =[];
                    $.each(checkedBox, function () {
                        obj.value.push($(this).val());
                    });
                    obj.value = obj.value.join(",");
                }
                
                let datetimeLength = $(dom).find("input[datetime='datetime']").length;
                let daterangeLength = $(dom).find("input[datetime='daterange']").length;
                let textLength = $(dom).find("input[type='text'][data-opera]").length;
                let hiddenLength = $(dom).find("input[type='hidden'][data-opera]").length;
                if(datetimeLength !=0 ){ obj.type="date";  }
                if(daterangeLength){
                    let val = $(dom).find("input[datetime='daterange']").val().split(' - ');
                    let field= $(dom).find("input[datetime='daterange']").attr("name");
                    if(val[0]){
                    	Array.push({
                            field: field,
                            //field: `date_format(${field},'%Y-%m-%d')`,
                            value: val[0],
                            opera: ">=",
                            type:"date"
                        });
	                    obj.field = field;
	                    obj.value = val[1];
	                    obj.opera="<=";
	                    obj.type="date";
                    }
                }
                
                if(textLength && !daterangeLength){
                    obj.opera=$(dom).find("input[type='text']").attr("data-opera");
                    obj.field = $(dom).find("input[type='text']").attr("name");
                    obj.value = $(dom).find("input[type='text']").val();
                }
                if(hiddenLength){
                    obj.opera=$(dom).find("input[type='hidden']").attr("data-opera");
                    obj.field = $(dom).find("input[type='hidden']").attr("name");
                    obj.value = $(dom).find("input[type='hidden']").val();
                }
                
                Array.push(obj); 
            }
            $.each($th.$el.find(".xw-search>div>.layui-input-inline"), function(index,dom) {
               _fn(dom)
            });
            $.each($th.$el.find(".xw-seniorSearch td"), function(index,dom) {
               _fn(dom)
            });
            let filter = [];
            if(dataField){
            	$.each(Array, function(index,obj) {
            		if(obj.field == dataField){
            			filter = obj.value;
            			return false;
            		}
            	});
            }else{
            	filter = $.map(Array,function(h){
	            	if(h.value) return h;
            	});
            }
            return filter;
        }
        
        //查询
        query(fn){
            if(fn) this._queryFn=fn;  
        }
        
        //重置数据
        emptyData(){
        	var hidden=this.$el.find(".xw-seniorSearch").is(":hidden");
            this._initHtml(this.$opt);
            this._queryFn(this.getData());
            if( this.$opt.searchBtnFixed != 'true' ){
            	if(hidden){
	            	this.$el.find(".xw-search .xw-searchQuery").show();
	        		this.$el.find(".xw-seniorSearch").hide();
	            }else{
	                this.$el.find(".xw-seniorSearch").show();
	                this.$el.find(".xw-search .xw-searchQuery").hide();
	            }
            }
            this._setHeight();
        }
        
        clickQuery(){
            this._queryFn( this.getData() );
        }
    }
    
    exports('search',{  render:function(opt){ return new Search(opt);  } });
});